import React, { useEffect, useState } from 'react';
import { Image, StyleSheet, Platform } from 'react-native';
import { Carousel, Grid } from '@ant-design/react-native';
import { IconX } from '@/rcomponents/iconx';
import Metrics from '@/Themes/Metrics';
import UserStore from '@/stores/userStore';
import HomeRoutes from './routeConfig';
import { ScrollView } from 'react-native-gesture-handler';
import Getui from 'react-native-getui';
import ApiClient from '@/services/apiClient';
import { Toast } from '@ant-design/react-native';

const styles = StyleSheet.create({
  wrapper: {
    height: Metrics.height / 4,
    marginLeft: 10,
  },
  containerHorizontal: {
    marginRight: 10,
    borderRadius: 10,
  },
  gridContainer: {},
});

const HomeScreen = ({ routes, navigation }) => {
  const [carouselIndex, setCarousel] = useState(0);
  const userStore = UserStore.useStore();
  useEffect(() => {
    userStore.getUser();
    // userStore.getUserIdCard();
    Getui.clientId(async (param) => {
      if (userStore.user.UserId !== '' && param !== '') {
        const res = await ApiClient.post('jcIdentity/v1/doSaveIfExists', {
          puUserTid: userStore.user.UserId,
          puClientId: param,
        });
        if (res.errorCode) {
          Toast.fail(res.errorMsg);
          return;
        }
      }
    });
  }, []);

  const gridRoute = HomeRoutes.filter(
    (homr) =>
      homr.gridOrder &&
      userStore.hasPermission(homr.component && homr.component.permission),
  )
    .sort((horl, horr) => horl.gridOrder - horr.gridOrder)
    .map((hor) => ({
      icon: hor.iconDef ? (
        <IconX origin={hor.iconDef.type} name={hor.iconDef.name} size={32} />
      ) : (
        <Image source={hor.imageSrc} />
      ),
      text: hor.title,
      route: hor.component && hor.component.routeName,
    }));

  const slides = [
    require('@/assets/images/home1.png'),
    require('@/assets/images/slide2.png'),
    require('@/assets/images/slide3.png'),
    require('@/assets/images/slide4.png'),
  ];
  return (
    <ScrollView>
      <ScrollView
        showsHorizontalScrollIndicator={false}
        horizontal={true}
        style={styles.wrapper}
      >
        {slides.map((slideimg, idx) => (
          <Image
            source={slideimg}
            key={idx}
            style={styles.containerHorizontal}
          />
        ))}
      </ScrollView>
      <Grid
        data={gridRoute}
        columnNum={Platform.isPad ? 5 : 4}
        hasLine={false}
        onPress={(el) => {
          if (el.route) {
            navigation.navigate(el.route);
          }
        }}
      />
    </ScrollView>
  );
};

HomeScreen.routeName = 'HomeScreen';
export default HomeScreen;
